package com.jian.service;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author Jiange
 * @create 2021-04-12-21:01
 */
public class Avater extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletInputStream inputStream = req.getInputStream();
        System.out.println("建哥");

        boolean multipartContent = ServletFileUpload.isMultipartContent(req);
        if(!multipartContent){
            resp.setStatus(403);
            return;
        }
        FileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(req);
            fileItems.forEach(e->{
                System.out.println(e.getFieldName());
                if(!e.isFormField()){
                    try {
                        File file = new File("D:\\WEB\\JavaWeb\\Project\\web\\WEB-INF\\image\\" + e.getName());
                        System.out.println(file.getAbsolutePath());
                        e.write(file);
                    } catch (Exception exception) {
                        exception.printStackTrace();
                        System.out.println("读入数据错误");
                    }
                }
            });
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
}
